package com.halachawiki.server;

import javax.servlet.http.HttpServletRequest;

import com.halachawiki.server.data.User;
import com.halachawiki.server.data.User.Privalege;
import com.halachawiki.server.data.UserContainer;
import com.halachawiki.shared.PermissionException;

public class PermissionManager {
	public static void checkSiteAccess(HttpServletRequest request) throws PermissionException {
		User user = UserContainer.getLogedInUser(request);
		if (!Settings.onlyRegisteredUsersCanRead) {
			return ;
		}
		validateUser(user);
	}
	
	// today we don't differentiate between 'write' and 'read' access, but this may change
	public static void checkSiteModify(HttpServletRequest request) throws PermissionException {
		checkSiteAccess(request);
	}
	
	public static void checkUserAdmin(HttpServletRequest request) throws PermissionException {
		User user = UserContainer.getLogedInUser(request);
		validateUser(user);
		if (user.getPrivalege() != Privalege.PRIVILEGED)
			throw new PermissionException();
	}

	// Not a full permission check.
	private static void validateUser(User user) throws PermissionException {
		if (user == null)
			throw new PermissionException();
		if (user.getBanned()) {
			throw new PermissionException();
		}
		if (Settings.usersNeedAdminApproval && !user.isApproved())
			throw new PermissionException();
		if (Settings.usersNeedConfirmation && !user.isConfirmed())
			throw new PermissionException();
	}

}
